package com.inhim.pjhim.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;

import com.google.gson.Gson;
import com.inhim.pjhim.R;
import com.inhim.pjhim.activity.ArticleActivity;
import com.inhim.pjhim.activity.CollectionNewActivity;
import com.inhim.pjhim.activity.RadioActivity;
import com.inhim.pjhim.activity.VideoActivity;
import com.inhim.pjhim.adapter.CollectionAdapter;
import com.inhim.pjhim.entity.CollectionList;
import com.inhim.pjhim.http.MyOkHttpClient;
import com.inhim.pjhim.http.Urls;
import com.inhim.pjhim.view.BToast;
import com.inhim.pjhim.view.TransparentProgressDialog;

import org.yczbj.ycrefreshviewlib.inter.OnLoadMoreListener;
import org.yczbj.ycrefreshviewlib.view.YCRefreshView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Request;

public class CollectionFragment extends Fragment{
    Gson gson=new Gson();
    private CollectionAdapter adapter;
    private YCRefreshView mRecyclerView;
    private int mPageNum=1;
    private Boolean refresh=true;
    private int totalPage;
    private List<CollectionList.List> historyList;
    private TransparentProgressDialog mProgressDialog;
    private Context mContext;
    private CollectionNewActivity mHistoryActivity;
    private Map<String,Integer> mDeviceHeaderMap = new HashMap();
    private List mKeyList=new ArrayList();
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_history, container, false);
        mContext=getActivity();
        mHistoryActivity= (CollectionNewActivity) getActivity();
        initView(view);
        handleRecyclerViewInfo();
        getHistoryList();
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void initView(View view) {
        mRecyclerView=view.findViewById(R.id.onceTask_member_ycView);
        historyList=new ArrayList<>();
    }

    public void showLoading(String text) {
        if (mProgressDialog == null) {
            mProgressDialog = new TransparentProgressDialog(mContext,text);
            mProgressDialog.getWindow().setDimAmount(0f);
            //mProgressDialog.setCancelable(false);
            mProgressDialog.setCanceledOnTouchOutside(false);
        }
        try{
            mProgressDialog.show();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void hideLoading() {
        try {
            if (mProgressDialog != null && mProgressDialog.isShowing()) {
                try{
                    mProgressDialog.dismiss();
                    mProgressDialog=null;
                }catch (Exception e){
                    e.printStackTrace();
                }
                mProgressDialog=null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public void getHistoryList() {
        showLoading("加载中");
        HashMap map=new HashMap();
        MyOkHttpClient.getInstance().asyncJsonPost(Urls.getCollectionList(mPageNum, 10,2),map, new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                BToast.showText("请求失败");
                hideLoading();
            }

            @Override
            public void onSuccess(Request request, String result) {
                hideLoading();
                //CollectionList historyEntity=GsonUtils.fromToJson(result,new TypeToken<List<CollectionList>>(){}.getType());
                CollectionList historyEntity = gson.fromJson(result, CollectionList.class);
                if (historyEntity.getCode() == 0) {
                    totalPage=historyEntity.getPage().getTotalPage();
                    if(refresh){
                        adapter.clear();
                        historyList.clear();
                    }
                    if(mPageNum>=totalPage){
                        adapter.pauseMore();
                    }
                    adapter.addAll(historyEntity.getPage().getList());
                    historyList.addAll(historyEntity.getPage().getList());
                    adapter.notifyDataSetChanged();
                } else {
                    BToast.showText(historyEntity.getMsg(), false);
                }
            }
        });
    }

    private void handleRecyclerViewInfo() {
        adapter = new CollectionAdapter(mContext);
        mRecyclerView.setAdapter(adapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setEmptyView(R.layout.empty_view_layout);
        mRecyclerView.setRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPageNum= 1;
                refresh=true;
                getHistoryList();
            }
        });

        //设置上拉加载更多时布局，以及监听事件
        adapter.setMore(R.layout.view_more, new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                //可以做请求下一页操作
                mPageNum++;
                refresh=false;
                getHistoryList();
            }
        });
        adapter.setOnItemClickListener(position -> {
            CollectionList.List data=adapter.getAllData().get(position);
            Intent intent;
            if(data.getStatus()!=null&&data.getStatus().equals("0")){

            }else{
                if(data.getReaderEntity().getType().equals("2")){
                    intent=new Intent(mContext, VideoActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                }else if(data.getReaderEntity().getType().equals("3")){
                    intent=new Intent(mContext, RadioActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                }else{
                    intent=new Intent(mContext, ArticleActivity.class);
                }
                intent.putExtra("ReaderId",data.getReaderEntity().getReaderId());
                startActivity(intent);
            }
        });

        adapter.setOnItemChildClickListener((view, position) -> {
            //CollectionList.List collection = adapter.getAllData().get(position);
            switch (view.getId()) {
                case R.id.checkbox:
                    CheckBox checkBox = (CheckBox) view;
                    if (!checkBox.isChecked()) {
                        mHistoryActivity.setAllCheck(false);
                        mDeviceHeaderMap.remove(String.valueOf(position));
                        mKeyList.remove(String.valueOf(position));
                    }else{
                        mDeviceHeaderMap.put(String.valueOf(position),position);
                        mKeyList.add(String.valueOf(position));
                    }
                    break;
            }
        });

    }

    public String getDeleteId(){
        if(mRecyclerView==null){
            return null;
        }

        StringBuilder stringBuilder=new StringBuilder();
        for (int i=0;i<mDeviceHeaderMap.size();i++){
            stringBuilder.append(historyList.get(mDeviceHeaderMap.get(String.valueOf(mKeyList.get(i)))).getVipBrowsingHistoryId());
            if(i!=mDeviceHeaderMap.size()-1){
                stringBuilder.append(",");
            }
        }
        return stringBuilder.toString();
    }

    public void editClick(boolean isCheck) {
        adapter.setCheck(isCheck,false);
        adapter.notifyDataSetChanged();
    }

    public void onCancel() {
        adapter.setCheck(true,false);
        adapter.notifyDataSetChanged();
    }

    public void setAllSelect(boolean isAll) {
        adapter.setCheck(true,isAll);
        adapter.notifyDataSetChanged();
    }

    public void notify(boolean refresh) {
        this.refresh=refresh;
        getHistoryList();
    }

}
